package cn.campsg.messageboard.controller;

import cn.campsg.messageboard.dao.UserDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register") // 添加注解确保Servlet能被正确映射
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 1. 获取参数并验证非空
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
//        String roleParam = request.getParameter("role");

        // 2. 参数基础验证
//        if (username == null || username.trim().isEmpty() ||
//                password == null || password.trim().isEmpty() ||
//                email == null || email.trim().isEmpty()
////                || roleParam == null
//        ) {
//            request.setAttribute("error", "字段不能为空");
//            request.getRequestDispatcher("register.jsp").forward(request, response);
//            return;
//        }

        // 3. 安全处理角色参数
//        int role;
//        try {
//            role = Integer.parseInt(roleParam);
//            if (role != 1 && role != 2) { // 只允许1或2
//                role = 1; // 默认设为普通用户
//            }
//        } catch (NumberFormatException e) {
//            role = 1; // 解析失败时设为默认值
//        }

        // 3. 直接设定默认角色
        int role = 1; // 默认普通用户

        // 4. 调用DAO注册用户
        UserDao userDao = new UserDao();
        boolean registered = userDao.registerUser(username, password, email, role);

        // 5. 处理结果
        if (registered) {
            response.sendRedirect("login.jsp");
        } else {
            request.setAttribute("error", "注册失败，用户名或邮箱可能已存在");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
}